<template>
    <el-row :gutter="40">
        <el-col :span="6">
            <el-form-item label="生产单号：">
                <el-input v-model="addTaskHead.head_no" placeholder="请输入生产单号" />
            </el-form-item>
        </el-col>
        <el-col :span="6">
        <el-form-item label="商品条码：">
            <el-input v-model="addTaskHead.product_code" placeholder="请输入生产单号" >
                <template v-slot:suffix>
                    <el-button 
                    size="mini" 
                    @click="lookProducthead" 
                    type="text" 
                    style="padding: 0; border: none; color: inherit;"
                    >
                    <el-icon style="vertical-align: middle">
                        <Search />
                    </el-icon>
                    </el-button>
                </template>
            </el-input>
        </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item label="商品名称：">
                <el-input v-model="addTaskHead.product_name" placeholder="请输入商品民成" />
            </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item label="计量单位：">
                <el-input v-model="addTaskHead.product_unit" placeholder="请输入计量单位" />
            </el-form-item>
        </el-col>
    </el-row>

    <el-row :gutter="40">
        <el-col :span="6">
            <el-form-item label="订购数量：">
                <el-input-number style="width:100%" :controls="false" v-model="addTaskHead.order_quantity"
                    placeholder="请输入采购价" />
            </el-form-item>
        </el-col>
        <el-col :span="6">
        <el-form-item label="生产数量：">
            <el-input-number style="width:100%" :controls="false" v-model="addTaskHead.production_quantity"
                    placeholder="请输入采购价" />
        </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item label="计划完工：">
                <el-date-picker value-format="YYYY-MM-DD hh:mm:ss" v-model="addTaskHead.finish_date" type="date" placeholder="请选择计划完工" style="width: 100%" />
            </el-form-item>
        </el-col>
        <el-col :span="6">
            <el-form-item label="单据备注：">
                <el-input autosize type="textarea" v-model="addTaskHead.remark" placeholder="请输入备注"/>
            </el-form-item>
        </el-col>
    </el-row>
  
    <div>
      <el-button type="primary" :icon="Plus" @click="addRow" >插入行</el-button>
      <el-button>扫码录入</el-button>
      <el-button>导入明细</el-button>
    </div>
    <div>
      <ul style="overflow: auto;height:25vh;width:90%" >
        <table style="color: black">
          <thead>
            <tr>
              <td><input type="checkbox" /></td>
              <td>仓库名称</td>
              <td>条码</td>
              <td>名称</td>
              <td>规格</td>
              <td>库存</td>
              <td>单位</td>
              <td>数量</td>
              <td>单价</td>
              <td>金额</td>
              <td>备注</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in tableData" :key="index">
              <td>
                <input type="checkbox" />
              </td>
              <td>
                <el-select placeholder="请选择仓库" v-model="item.depot_id" style="width:100px"  clearable>
                  <el-option v-for="item in warehouseList" :key="item.depot_id" :label="item.depot_name"
                :value="item.depot_id" />
                </el-select>
              </td>
              <td>
                <el-input placeholder="输入条码或名称" v-model="item.bar_code" >
                    <template v-slot:suffix>
                        <el-button 
                        size="mini" 
                        @click="lookProduct" 
                        type="text" 
                        style="padding: 0; border: none; color: inherit;"
                        >
                        <el-icon style="vertical-align: middle">
                            <Search />
                        </el-icon>
                        </el-button>
                    </template>
                </el-input>
              </td>
              <td>
                <el-input v-model="item.product_name" placeholder="请输入商品名称"/>
              </td>
              <td>
                <el-input v-model="item.standard" />
              </td>
              <td>
                <el-input v-model="item.current_number" />
              </td>
              <td>
                <el-input v-model="item.unit" />
              </td>
              <td>
                <el-input-number style="width:100%" :controls="false" v-model="item.oper_number"
                placeholder="请输入购买数量" />
              </td>
              <td>
                <el-input-number style="width:100%" :controls="false" v-model="item.unit_price"
                placeholder="请输入商品单价" />
              </td>
              <td>
                <el-input-number style="width:100%" :controls="false" v-model="calculatedAmount[index]"
                placeholder="商品总金额" />
              </td>
              <td>
                <el-input v-model="item.remark" />
              </td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td>{{getNumAndPrice.Num.toFixed(2)}}</td>
              <td></td>
              <td>{{getNumAndPrice.Price.toFixed(2)}}</td>
            </tr>
          </tbody>
        </table>
      </ul>
    </div>
    <div  style="float:right;margin-top:50px">
      <el-button type="primary" @click="Save">
        提交
      </el-button>
      <el-button @click="resetForm()">取消</el-button>
    </div>
  
  
    <el-dialog v-model="dialogTableVisible" title="商品信息" destroy-on-close style="width: 50%;height:70%">
        <el-row :gutter="20" style="width: 700px;">
            <el-col :span="6">
                <el-form-item label="商品">
                <el-input v-model="form.name" />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item>
                <el-button type="primary" @click="getproductData">查询</el-button>
                </el-form-item>
            </el-col>
        </el-row>
      <el-table :data="productData" style="width: 100%;height:40vh"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="#" width="55">
        <template v-slot="scope">
          {{ scope.$index + 1 }}  <!-- 自增数字，从1开始 -->
        </template>
      </el-table-column>
        <el-table-column  prop="bar_code" label="条码" />
        <el-table-column  prop="product_name" label="名称" />
        <el-table-column  prop="standard" label="规格" />
        <el-table-column  prop="model" label="型号" />
        <el-table-column  prop="name" label="类别" />
        <el-table-column  prop="unit" label="单位" />
      </el-table>
      <div  style="float:right;margin-top:50px">
      <el-button type="primary" @click="AddProduct">
        提交
      </el-button>
      <el-button @click="ResetProduct">取消</el-button>
    </div>
      <template #footer>
        <div class="dialog-footer">
          <el-pagination
          v-model:current-page="form.PageIndex"
          v-model:page-size="form.PageSize"
          :page-sizes="[10,20,30]"
          layout=" prev, pager, next, sizes"
          :total="1000"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          />
        </div>
      </template>
      <!--分页-->
    <div style="float:right">
        
    </div>
  </el-dialog>
</template>
  
<script lang="ts" setup>
  import {reactive,ref,onMounted,computed} from 'vue'
  import {useRoute,useRouter} from 'vue-router'
  import {ElMessage,ElMessageBox} from 'element-plus'
  import moment from 'moment';
  import {  Minus, Plus } from '@element-plus/icons-vue';
  import {GetProductionBow,AddProductionTaskHead,GetMaterialNeedById} from '@/api/production/index'
  import {type productionBom,type ProductionTaskHead,type MaterialNeedData} from '@/api/production/type'
  import {GetSupplierList, GetWarehouseList } from '@/api/Sales/index'
  
  const router=useRouter()

  //供应商列表
  const supplierList: any = ref([])
  const getSupplierList = async () => {
    await GetSupplierList().then(res => {
        supplierList.value = res.data;
    })
  }
  
  //仓库列表
  const warehouseList: any = ref([])
  const getWarehouseList = async () => {
    await GetWarehouseList().then(res => {
        warehouseList.value = res.data;
    })
  }
  const form3=ref<MaterialNeedData>({
    productid:null,
    PageIndex:1,
    PageSize:10,
})
  //子页面
  const AddProduct=async()=>{
    if(addtype.value==1){
        multipleSelection.value.forEach(p=>{
            tableData.value.push(p)
        })
    }else{
        if(multipleSelection.value.length>1){
            ElMessage.error("只能选择一项")
            return
        }else{
            console.log(multipleSelection.value)
            form3.value.productid= multipleSelection.value.map((d:any)=>d.productid)[0]
            const res = await GetMaterialNeedById(form3.value);
            addTaskHead.product_id=res.data.data[0].productid
            addTaskHead.product_code=res.data.data[0].bar_code
            addTaskHead.product_name=res.data.data[0].product_name
            addTaskHead.product_unit=res.data.data[0].unit
            addTaskHead.order_quantity=1
            addTaskHead.production_quantity=1
        }
    }

  dialogTableVisible.value=false
  }
  const ResetProduct=()=>{
  dialogTableVisible.value=false
  }
  
  const multipleSelection = ref([])
  const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
    console.log(multipleSelection.value)
  }
  
  const form=ref<productionBom>({
    name:'',
    categoryid:null,
    PageIndex:1,
    PageSize:10
  
  })
  const productData = ref([])
  const getproductData = async () => {
  await GetProductionBow(form.value)
    .then(res => {
      console.log(res.data.data)
      productData.value = res.data.data
    })
  }
  const handleSizeChange = (val: number) => {
  form.value.PageSize=val;
  getproductData()
  }
  const handleCurrentChange = (val: number) => {
  form.value.PageIndex=val;
  getproductData()
  }
  const dialogTableVisible=ref(false)
  const addtype=ref(1)
  const lookProduct=()=>{
    addtype.value=1
  dialogTableVisible.value=true
  }
  const lookProducthead=()=>{
    addtype.value=2
  dialogTableVisible.value=true
  }
  //主页面
  const addTaskHead=reactive<ProductionTaskHead>({
    head_no:'SX'+ moment().format('YYYYMMDDHHmmssSSS'),
    product_id:null,
    product_code:'',
    product_name:'',
    product_unit:'',
    order_quantity:null,
    production_quantity:null,
    bom_quantity:null,
    bom_allPrice:null,
    finish_date:null,
    remark:'',
    items:[{
        product_id:0,
        bar_code:'',
        product_name:'',
        standard:'',
        model:'',
        color:'',
        product_unit:'',
        oper_number:0,
        unit_price:0,
        all_price:0,
        remark:'',
        depot_id:0,
        another_depot_id:2
    }]
  })
  
  const Save=async()=>{
  console.log(addTaskHead.finish_date)
  addOtheritem()
  addTaskHead.items=addTaskHead.items.filter(p=>p.product_id!=0)as any
  addTaskHead.bom_quantity=getNumAndPrice.value.Num
  addTaskHead.bom_allPrice=getNumAndPrice.value.Price
  console.log(addTaskHead)
  await AddProductionTaskHead(addTaskHead)
  .then(res => {
    if(res.data.code>0){
      ElMessage.success(res.data.message)
      location.reload()
    }else{
      ElMessage.error(res.data.message)
      return
    }
  })
  }
  const resetForm=()=>{
  router.push('/StashManagement/StashWarehousing')
  }
  const tableData = ref([{
    productid:0,
    bar_code:'',
    product_name:'',
    standard:'',
    model:'',
    color:'',
    product_unit:'',
    sku:'',
    oper_number:0,
    unit_price:0,
    all_price:0,
    remark:'',
    depot_id:0,
    another_depot_id:0,
    current_number:0,
    unit:''
  }]);
  const addOtheritem=()=>{
  tableData.value.filter(p=>p.productid!=0).forEach(item=>{
    const newItem = {
         product_id: item.productid,
         bar_code: item.bar_code,
         product_name: item.product_name,
         standard: item.standard,
         model: item.model,
         color: item.color,
         product_unit: item.unit,
         oper_number: item.oper_number,
         unit_price: item.unit_price,
         all_price: item.oper_number * item.unit_price,
         remark: item.remark,
         depot_id: item.depot_id,
         another_depot_id: 2
       };
       addTaskHead.items.push(newItem);
  })
  }
  
  const addRow = () => {
  tableData.value.push({
    productid:0,
    bar_code:'',
    product_name:'',
    standard:'',
    model:'',
    color:'',
    product_unit:'',
    sku:'',
    oper_number:0,
    unit_price:0,
    all_price:0,
    remark:'',
    depot_id:0,
    another_depot_id:0,
    current_number:0,
    unit:''
  });
  };
  
  const getNumAndPrice=computed(()=>{
  let Num=0
  let Price=0
  tableData.value.forEach(c=>{
    Num+=c.oper_number*1.0
    Price+=c.oper_number*c.unit_price
  })
  if(Number.isNaN(Num)){
    Num=0
    Price=0
  }
  if(Number.isNaN(Price)){
    Num=0
    Price=0
  }
  
  return {
    Num:Num,
    Price:Price
  }
  })
  
  const calculatedAmount=computed(()=>{
      return tableData.value.map(item => {
        return item.oper_number * item.unit_price;
      });
  })
  
  onMounted(()=>{
  getproductData()
  getWarehouseList()
  getSupplierList()
  })
</script>
  
<style scoped>
  .el-row {
  margin-bottom: 5px;
  }
  .el-row:last-child {
  margin-bottom: 0;
  }
  .el-col {
  border-radius: 4px;
  }
  
  .grid-content {
  border-radius: 4px;
  min-height: 36px;
  }
  
</style>